package HTTP

import (
	"SQL/FSDB"
	"logs"
	"net/http"
)

type loginInfo struct {
	UserName  string
	IconName  string
	IsManager bool
}

func login(w http.ResponseWriter, req *http.Request) {

	var resCode = Success
	var msg = ""
	var res interface{}
	defer func() {
		writeResult(w, resCode, msg, res)
	}()

	if req.Method != "POST" {
		msg = "请使用 POST 方式登录！"
		return
	}

	account := req.FormValue("userID")
	password := req.FormValue("password")
	ok := false
	if ok, resCode, msg = isArgsEmpty(account, password); ok {
		return
	}
	if ok, resCode, msg = isValidID(account, "UserID"); !ok {
		return
	}
	if ok, resCode, msg = isExistUserID(account); !ok {
		return
	}
	if ok, resCode, msg = isValidPwd(password); !ok {
		return
	}

	errCode, errMsg, loginData := checkLogin(account, password)
	msg = errMsg
	if errCode != Success {
		resCode = errCode
		return
	}
	res = loginData
}

func checkLogin(account string, pwd string) (errCode int, errMsg string, info interface{}) {

	sql := `SELECT nickname,password,icon,u.isManager 
			FROM users u,objects o 
			WHERE o.id = $1 AND u.id = o.id`
	rows, err := FSDB.Query(sql, account)
	defer rows.Close()
	if err != nil {
		logs.Print("checkLoginInfo出错，err:", err.Error())
		return errDBQueryFailed, err.Error(), nil
	}
	if rows.Next() {
		var nickname string
		var password string
		var icon string
		var isManager bool
		err := rows.Scan(&nickname, &password, &icon, &isManager)
		if err != nil {
			logs.Print("checkLoginInfo rows.Scan出错，err:", err.Error())
			return errDBQueryFailed, err.Error(), nil
		}
		if password == pwd {
			return Success, account + " 登录成功！", loginInfo{nickname, icon, isManager}
		}
	} else {
		return errAccountNotExist, "帐号不存在！", nil
	}
	return errPasswordWrong, "密码错误！", nil
}
